package defs

import (
	"encoding/json"
	"io"
	"net/http"
)

var (
	ErrorRequestBodyParseFailed = ErrorResponse{
		HttpStatusCode: 400, Error: Err{"Request body is not correct", "1400"}}

	ErrorNotAuthUser = ErrorResponse{
		HttpStatusCode: 401, Error: Err{"User authentication failed", "1401"}}

	ErrorAuthExpired = ErrorResponse{
		HttpStatusCode: 403, Error: Err{"用户信息失效, 请返回首页重新登录", "14011"}}

	ErrorNotFound = ErrorResponse{
		HttpStatusCode: 404, Error: Err{"Resource not found", "1404"}}

	ErrorDBError = ErrorResponse{
		HttpStatusCode: 500, Error: Err{ErrorMsg: "DB ops failed", ErrorCode: "1500"}}

	ErrorInternalFaults = ErrorResponse{
		HttpStatusCode: 500, Error: Err{ErrorMsg: "Internal service error", ErrorCode: "1501"}}
)

type Err struct {
	ErrorMsg  string `json:"error"`
	ErrorCode string `json:"error_code"`
}

type ErrorResponse struct {
	HttpStatusCode int
	Error          Err
}

func SendSuccessResponse(w http.ResponseWriter, data string, statusCode int) {
	w.Header().Set("Content-Type", "application/json")
	//w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(statusCode)
	io.WriteString(w, data)
}

func SendErrorResponse(w http.ResponseWriter, response ErrorResponse) {
	w.WriteHeader(response.HttpStatusCode)
	resJson, _ := json.Marshal(&response.Error)
	io.WriteString(w, string(resJson))
}
